package com.doule.farmerassistant.plan;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.doule.farmerassistant.DeathConfig;
import com.doule.farmerassistant.R;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;

import java.io.IOException;

/**
 * download apk from server.
 * 
 * @author happy
 * 
 */
public final class StartPlanTask {

    /**
     * Constructor.
     * 
     * @param context
     *            Context.
     * @param id
     *            plan id.
     * @param token
     *            Authentication token
     */
    public StartPlanTask(Context context, final String id, final String token) {
        mContext = context;
        mid = id;
        mToken = token;
    }

    /**
     * Context.
     */
    private Context mContext;

    /**
     * 
     */
    private String mServerUrl, mid, mToken;

    /**
     * Stop plan task.
     * @return true if stop plan success.
     */
    private boolean stopPlanTask() {

        mServerUrl = DeathConfig.getServerUrl();
        if (mServerUrl == null) {
            return false;
        }

        Log.e("LoadMessageTask", "server url: " + mServerUrl);
        HttpPost request = new HttpPost(mServerUrl + "/startPlan");
        request.setHeader("content-type", "application/octet-stream");
        request.setHeader("planId", mid);
        request.setHeader("tk", mToken);

        AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        try {
            HttpResponse resp = client.execute(request);
            Header head = resp.getFirstHeader("error");
            if (null != head) {
                String error = head.getValue();
                Log.e("UserLoginTask", "login error: " + error);
                return false;
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return false;
    }

    /**
     * worker runnable object.
     */
    private final Runnable worker = new Runnable() {

        @Override
        public void run() {
            boolean task = stopPlanTask();
            if (task) {
                Looper.prepare();
                Toast.makeText(mContext,
                        mContext.getString(R.string.open_plan_success),
                        Toast.LENGTH_LONG).show();
                Looper.loop();
            } else {
                Looper.prepare();
                Toast.makeText(mContext,
                        mContext.getString(R.string.open_plan_fail),
                        Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }
    };

    /**
     * start working thread.
     */
    public void go() {
        new Thread(worker).start();
    }
}
